import { defineComponent, onMounted, type PropType, ref, watch } from "vue";
import { dictOptions, type SimpleDict } from "@/api/system";

export default defineComponent({
  name: "DictOption",
  props: {
    value: {
      type: Object
    },
    type: {
      type: String as PropType<"select" | "radio">,
      required: true
    },
    code: {
      type: String,
      required: true
    },
    size: {
      type: String as PropType<"default" | "large" | "small">,
      default: "default"
    },
    placeholder: {
      type: String,
      default: "请选择"
    }
  },
  emits: ["update:value"],
  setup(props, { emit }) {
    const data = ref<Array<SimpleDict>>([]);
    const val = ref(props.value);
    watch(val, newVal => emit("update:value", newVal), {
      deep: true
    });
    watch(
      () => props.code,
      () => {
        dictOptions(props.code).then(res => {
          data.value = res;
        });
      }
    );
    onMounted(() => {
      dictOptions(props.code).then(res => {
        data.value = res;
      });
    });
    return () => {
      if (props.type === "select") {
        return (
          <el-select-v2
            clearable={true}
            v-model={val.value}
            placeholder={props.placeholder}
            size={props.size}
            options={data.value}
            class="!w-[200px]"
          />
        );
      } else if (props.type === "radio") {
        return (
          <el-radio-group v-model={val.value}>
            {data.value.map((item, index) => {
              return (
                <el-radio key={index} value={item.value} size={props.size}>
                  {item.label}
                </el-radio>
              );
            })}
          </el-radio-group>
        );
      } else {
        return null;
      }
    };
  }
});
